package com.itheima.factory;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/*
    创建dao代理对象
 */
public class DaoInstanceFactory {
    private static SqlSessionFactory factory;

    static {
        try {
            // 加载核心配置文件
            InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");

            // 初始化工厂
            factory = new SqlSessionFactoryBuilder().build(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    // 获取SqlSession
    public static SqlSession getSqlSession() {
        return factory.openSession();
    }


    public static <T> T getMapper(Class<T> daoInstanceClass) {  // UserDao.class
        //1. 获取SqlSession
        SqlSession sqlSession = getSqlSession();

        //2. 创建dao代理对象并返回
        T t = sqlSession.getMapper(daoInstanceClass);  // UserDao 接口的代理对象

        //3. 对t进行方法增强
        T proxy_t = (T) Proxy.newProxyInstance(t.getClass().getClassLoader(), t.getClass().getInterfaces(), new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                Object value = null;
                try {
                    // 对方法进行增强
                    value = method.invoke(t, args);
                    // 成功: 提交事务
                    sqlSession.commit();
                } catch (Exception e) {
                    // 失败: 回滚事务
                    sqlSession.rollback();
                    throw new RuntimeException(e);
                    //记录日志
                } finally {
                    try {
                        // 关闭连接
                        sqlSession.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                return value;
            }
        });
        // 返回增强以后的dao代理对象
        return proxy_t;
    }
}
